// 全局变量
let heartData = [];
let isDataLoaded = false;
let predictionHistory = [];

// 页面加载完成后执行
window.addEventListener('DOMContentLoaded', function() {
    // 加载数据
    loadHeartData();
    
    // 加载预测历史
    loadPredictionHistory();
    
    // 设置导航功能
    setupNavigation();
    
    // 设置表单提交事件
    document.getElementById('prediction-form').addEventListener('submit', function(e) {
        e.preventDefault();
        makePrediction();
    });
});

// 加载CSV数据
function loadHeartData() {
    fetch('heart.csv')
        .then(response => response.text())
        .then(data => {
            // 解析CSV数据
            const rows = data.trim().split('\n');
            const headers = rows[0].split(',');
            
            for (let i = 1; i < rows.length; i++) {
                const values = rows[i].split(',');
                const rowData = {};
                
                for (let j = 0; j < headers.length; j++) {
                    // 转换数值类型
                    rowData[headers[j]] = parseFloat(values[j]);
                }
                
                heartData.push(rowData);
            }
            
            // 添加示例数据用于统计展示
            addSampleData();
            
            isDataLoaded = true;
            console.log('数据加载完成，共', heartData.length, '条记录');
            
            // 数据加载完成后初始化统计图表
            if (document.getElementById('statistics').style.display !== 'none') {
                initStatistics();
            }
        })
        .catch(error => {
            console.error('加载数据失败:', error);
            // 如果加载失败，添加一些示例数据
            addSampleData();
            isDataLoaded = true;
        });
}

// 添加示例数据
function addSampleData() {
    // 生成10条随机示例数据
    const sampleData = [
        { age: 45, sex: 1, cp: 1, trestbps: 125, chol: 210, fbs: 0, restecg: 1, thalach: 168, exang: 0, oldpeak: 1.2, slope: 2, ca: 0, thal: 2, target: 0, isSample: true },
        { age: 62, sex: 1, cp: 2, trestbps: 140, chol: 268, fbs: 0, restecg: 0, thalach: 160, exang: 1, oldpeak: 3.6, slope: 0, ca: 2, thal: 3, target: 1, isSample: true },
        { age: 54, sex: 0, cp: 0, trestbps: 130, chol: 256, fbs: 1, restecg: 1, thalach: 163, exang: 0, oldpeak: 0.6, slope: 2, ca: 0, thal: 2, target: 0, isSample: true },
        { age: 58, sex: 1, cp: 3, trestbps: 150, chol: 280, fbs: 0, restecg: 0, thalach: 145, exang: 1, oldpeak: 2.4, slope: 1, ca: 1, thal: 3, target: 1, isSample: true },
        { age: 41, sex: 0, cp: 1, trestbps: 120, chol: 199, fbs: 0, restecg: 1, thalach: 180, exang: 0, oldpeak: 0, slope: 2, ca: 0, thal: 2, target: 0, isSample: true },
        { age: 53, sex: 1, cp: 0, trestbps: 145, chol: 233, fbs: 0, restecg: 1, thalach: 155, exang: 1, oldpeak: 1.3, slope: 1, ca: 1, thal: 3, target: 1, isSample: true },
        { age: 48, sex: 1, cp: 2, trestbps: 130, chol: 240, fbs: 1, restecg: 1, thalach: 172, exang: 0, oldpeak: 0.2, slope: 2, ca: 0, thal: 2, target: 0, isSample: true },
        { age: 65, sex: 1, cp: 3, trestbps: 160, chol: 286, fbs: 0, restecg: 0, thalach: 125, exang: 1, oldpeak: 3.2, slope: 0, ca: 3, thal: 3, target: 1, isSample: true },
        { age: 39, sex: 0, cp: 1, trestbps: 118, chol: 183, fbs: 0, restecg: 1, thalach: 190, exang: 0, oldpeak: 0, slope: 2, ca: 0, thal: 2, target: 0, isSample: true },
        { age: 57, sex: 1, cp: 0, trestbps: 135, chol: 254, fbs: 0, restecg: 1, thalach: 148, exang: 1, oldpeak: 2.0, slope: 1, ca: 2, thal: 3, target: 1, isSample: true }
    ];
    
    // 添加示例数据到总数据中
    heartData.push(...sampleData);
    
    // 为示例数据创建预测历史记录
    sampleData.forEach((data, index) => {
        const historyItem = {
            input: { ...data },
            result: {
                prediction: data.target,
                probability: data.target === 1 ? 0.75 : 0.35,
                riskLevel: data.target === 1 ? '高风险' : '低风险'
            },
            timestamp: new Date(Date.now() - (10 - index) * 86400000).toISOString(), // 模拟过去10天的数据
            isSample: true
        };
        delete historyItem.input.target;
        delete historyItem.input.isSample;
        predictionHistory.push(historyItem);
    });
    
    // 保存到本地存储
    localStorage.setItem('heartDiseasePredictionHistory', JSON.stringify(predictionHistory));
}

// 设置导航功能
function setupNavigation() {
    const navLinks = document.querySelectorAll('nav a');
    const sections = document.querySelectorAll('main section');
    
    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            // 更新活动链接样式
            navLinks.forEach(item => item.classList.remove('active'));
            this.classList.add('active');
            
            // 隐藏所有部分
            sections.forEach(section => section.style.display = 'none');
            
            // 显示对应部分
            const targetId = this.getAttribute('href').substring(1);
            const targetSection = document.getElementById(targetId);
            targetSection.style.display = 'block';
            
            // 如果是统计部分，确保初始化统计图表，包含用户预测数据
            if (targetId === 'statistics' && isDataLoaded) {
                updatePredictionHistoryTable();
                initStatistics(); // 重新初始化所有统计图表
            }
        });
    });
}



// 简单的机器学习模型 - 使用逻辑回归的简化版本
function predictHeartDisease(inputData) {
    // 特征权重（基于简单的统计分析设置）
    const weights = {
        age: 0.04,
        sex: 0.25,
        cp: 0.20,
        trestbps: 0.01,
        chol: 0.001,
        fbs: 0.1,
        restecg: 0.1,
        thalach: -0.01,
        exang: 0.25,
        oldpeak: 0.15,
        slope: 0.1,
        ca: 0.2,
        thal: 0.15
    };
    
    // 计算加权和
    let score = 0;
    for (const feature in inputData) {
        if (weights.hasOwnProperty(feature)) {
            score += inputData[feature] * weights[feature];
        }
    }
    
    // 使用sigmoid函数将分数转换为概率
    const probability = 1 / (1 + Math.exp(-(score - 2.5)));
    
    // 根据概率判断结果
    const prediction = probability > 0.5 ? 1 : 0;
    
    return {
        prediction: prediction,
        probability: probability,
        riskLevel: getRiskLevel(probability)
    };
}

// 获取风险等级
function getRiskLevel(probability) {
    if (probability < 0.3) return '低风险';
    if (probability < 0.7) return '中等风险';
    return '高风险';
}

// 获取健康建议
function getHealthSuggestions(probability, inputData) {
    const suggestions = [];
    
    if (probability > 0.7) {
        suggestions.push('建议尽快咨询心脏科医生，进行详细检查');
        suggestions.push('考虑调整生活方式，减少高脂肪、高盐食物摄入');
    } else if (probability > 0.3) {
        suggestions.push('定期进行体检，监测心脏健康状况');
        suggestions.push('增加有氧运动，如散步、游泳等');
    } else {
        suggestions.push('保持健康的生活方式，继续预防心血管疾病');
        suggestions.push('定期体检，维持良好的健康状态');
    }
    
    // 根据具体指标给出建议
    if (inputData.trestbps > 140) {
        suggestions.push('血压偏高，建议减少盐分摄入，保持规律作息');
    }
    
    if (inputData.chol > 240) {
        suggestions.push('胆固醇偏高，建议低脂饮食，增加膳食纤维摄入');
    }
    
    if (inputData.thalach < 120) {
        suggestions.push('最大心率偏低，可在医生指导下适当增加运动量');
    }
    
    return suggestions;
}

// 处理表单提交，进行预测
function makePrediction() {
    // 收集表单数据
    const inputData = {
        age: parseFloat(document.getElementById('age').value),
        sex: parseFloat(document.getElementById('sex').value),
        cp: parseFloat(document.getElementById('cp').value),
        trestbps: parseFloat(document.getElementById('trestbps').value),
        chol: parseFloat(document.getElementById('chol').value),
        fbs: parseFloat(document.getElementById('fbs').value),
        restecg: parseFloat(document.getElementById('restecg').value),
        thalach: parseFloat(document.getElementById('thalach').value),
        exang: parseFloat(document.getElementById('exang').value),
        oldpeak: parseFloat(document.getElementById('oldpeak').value),
        slope: parseFloat(document.getElementById('slope').value),
        ca: parseFloat(document.getElementById('ca').value),
        thal: parseFloat(document.getElementById('thal').value)
    };
    
    // 进行预测
    const result = predictHeartDisease(inputData);
    
    // 显示预测结果
    const resultContainer = document.querySelector('#prediction-result .result-content');
    const predictionText = result.prediction === 1 ? 
        `<div class="result-item"><strong>预测结果：</strong> <span style="color: #f44336;">高风险</span></div>` : 
        `<div class="result-item"><strong>预测结果：</strong> <span style="color: #4caf50;">低风险</span></div>`;
    
    resultContainer.innerHTML = predictionText + 
        `<div class="result-item"><strong>风险概率：</strong> ${Math.round(result.probability * 100)}%</div>` +
        `<div class="result-item"><strong>风险等级：</strong> ${result.riskLevel}</div>`;
    
    // 更新风险条
    const riskBar = document.getElementById('risk-bar');
    const riskProgressBar = document.getElementById('risk-progress-bar');
    const riskPercentage = document.getElementById('risk-percentage');
    
    riskBar.style.display = 'block';
    riskProgressBar.style.width = `${result.probability * 100}%`;
    riskPercentage.textContent = `${Math.round(result.probability * 100)}%`;
    
    // 显示健康建议
    const suggestions = document.getElementById('suggestions');
    const suggestionsList = document.getElementById('suggestions-list');
    
    suggestions.style.display = 'block';
    suggestionsList.innerHTML = '';
    
    const healthSuggestions = getHealthSuggestions(result.probability, inputData);
    healthSuggestions.forEach(suggestion => {
        const li = document.createElement('li');
        li.textContent = suggestion;
        suggestionsList.appendChild(li);
    });
    
    // 保存预测历史
    savePredictionHistory(inputData, result);
}

// 初始化统计图表
function initStatistics() {
    if (!isDataLoaded) return;
    
    // 患病率饼图
    createPrevalenceChart();
    
    // 性别分布图表
    createGenderChart();
    
    // 年龄分布图表
    createAgeChart();
    
    // 相关性分析图表
    createCorrelationChart();
    
    // 更新预测历史表格
    updatePredictionHistoryTable();
}

// 创建患病率饼图
function createPrevalenceChart() {
    const healthyCount = heartData.filter(d => d.target === 0).length;
    const diseaseCount = heartData.filter(d => d.target === 1).length;
    
    const chart = echarts.init(document.getElementById('prevalence-chart'));
    const option = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            left: 'left'
        },
        series: [
            {
                name: '健康状况',
                type: 'pie',
                radius: '50%',
                data: [
                    { value: healthyCount, name: '健康' },
                    { value: diseaseCount, name: '患病' }
                ],
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };
    chart.setOption(option);
    
    // 响应式处理
    window.addEventListener('resize', function() {
        chart.resize();
    });
}

// 创建性别分布图表
function createGenderChart() {
    const maleHealthy = heartData.filter(d => d.sex === 1 && d.target === 0).length;
    const maleDisease = heartData.filter(d => d.sex === 1 && d.target === 1).length;
    const femaleHealthy = heartData.filter(d => d.sex === 0 && d.target === 0).length;
    const femaleDisease = heartData.filter(d => d.sex === 0 && d.target === 1).length;
    
    const chart = echarts.init(document.getElementById('gender-chart'));
    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: ['健康', '患病']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: ['男性', '女性']
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '健康',
                type: 'bar',
                stack: 'total',
                emphasis: {
                    focus: 'series'
                },
                data: [maleHealthy, femaleHealthy]
            },
            {
                name: '患病',
                type: 'bar',
                stack: 'total',
                emphasis: {
                    focus: 'series'
                },
                data: [maleDisease, femaleDisease]
            }
        ]
    };
    chart.setOption(option);
    
    // 响应式处理
    window.addEventListener('resize', function() {
        chart.resize();
    });
}

// 创建年龄分布图表
function createAgeChart() {
    // 按年龄分组
    const ageGroups = {};
    heartData.forEach(d => {
        const ageGroup = Math.floor(d.age / 10) * 10;
        if (!ageGroups[ageGroup]) {
            ageGroups[ageGroup] = { healthy: 0, disease: 0 };
        }
        if (d.target === 0) {
            ageGroups[ageGroup].healthy++;
        } else {
            ageGroups[ageGroup].disease++;
        }
    });
    
    // 准备数据
    const ages = Object.keys(ageGroups).sort((a, b) => a - b);
    const healthyData = ages.map(age => ageGroups[age].healthy);
    const diseaseData = ages.map(age => ageGroups[age].disease);
    
    const chart = echarts.init(document.getElementById('age-chart'));
    const option = {
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['健康', '患病']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ages.map(age => `${age}-${parseInt(age) + 9}`)
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '健康',
                type: 'line',
                stack: 'Total',
                areaStyle: {},
                emphasis: {
                    focus: 'series'
                },
                data: healthyData
            },
            {
                name: '患病',
                type: 'line',
                stack: 'Total',
                areaStyle: {},
                emphasis: {
                    focus: 'series'
                },
                data: diseaseData
            }
        ]
    };
    chart.setOption(option);
    
    // 响应式处理
    window.addEventListener('resize', function() {
        chart.resize();
    });
}

// 创建相关性分析图表
function createCorrelationChart() {
    // 计算各特征与目标变量的相关性
    const features = ['age', 'trestbps', 'chol', 'thalach', 'oldpeak'];
    const correlations = [];
    
    features.forEach(feature => {
        let sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0, sumY2 = 0;
        const n = heartData.length;
        
        heartData.forEach(d => {
            sumX += d[feature];
            sumY += d.target;
            sumXY += d[feature] * d.target;
            sumX2 += d[feature] * d[feature];
            sumY2 += d.target * d.target;
        });
        
        // 皮尔逊相关系数
        const correlation = (n * sumXY - sumX * sumY) / 
            Math.sqrt((n * sumX2 - sumX * sumX) * (n * sumY2 - sumY * sumY));
        
        correlations.push(Math.abs(correlation));
    });
    
    const chart = echarts.init(document.getElementById('correlation-chart'));
    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'value',
            max: 1
        },
        yAxis: {
            type: 'category',
            data: ['年龄', '血压', '胆固醇', '最大心率', 'ST段压低']
        },
        series: [
            {
                name: '相关性',
                type: 'bar',
                data: correlations,
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                        { offset: 0, color: '#83bff6' },
                        { offset: 0.5, color: '#188df0' },
                        { offset: 1, color: '#188df0' }
                    ])
                }
            }
        ]
    };
    chart.setOption(option);
    
    // 响应式处理
    window.addEventListener('resize', function() {
        chart.resize();
    });
}

// 保存预测历史到本地存储并添加到统计数据
function savePredictionHistory(inputData, result) {
    const historyItem = {
        input: inputData,
        result: result,
        timestamp: new Date().toISOString()
    };
    
    predictionHistory.push(historyItem);
    
    // 限制历史记录数量
    if (predictionHistory.length > 20) {
        predictionHistory.shift();
    }
    
    // 保存到本地存储
    localStorage.setItem('heartDiseasePredictionHistory', JSON.stringify(predictionHistory));
    
    // 将用户输入的数据添加到统计数据中（标记为用户输入数据）
    const userInputData = { ...inputData, target: result.prediction, isUserInput: true };
    heartData.push(userInputData);
    
    // 如果当前在统计页面，更新表格和图表
    if (document.getElementById('statistics').style.display !== 'none') {
        updatePredictionHistoryTable();
        initStatistics(); // 重新初始化统计图表以包含新数据
    }
}

// 从本地存储加载预测历史
function loadPredictionHistory() {
    const savedHistory = localStorage.getItem('heartDiseasePredictionHistory');
    if (savedHistory) {
        predictionHistory = JSON.parse(savedHistory);
    }
}

// 更新预测历史表格
function updatePredictionHistoryTable() {
    const tableBody = document.querySelector('#prediction-history tbody');
    tableBody.innerHTML = '';
    
    // 按时间倒序显示
    const sortedHistory = [...predictionHistory].reverse();
    
    sortedHistory.forEach(item => {
        const row = document.createElement('tr');
        
        const ageCell = document.createElement('td');
        ageCell.textContent = item.input.age;
        
        const sexCell = document.createElement('td');
        sexCell.textContent = item.input.sex === 1 ? '男' : '女';
        
        const resultCell = document.createElement('td');
        const resultText = item.result.prediction === 1 ? '高风险' : '低风险';
        resultCell.textContent = resultText;
        resultCell.style.color = item.result.prediction === 1 ? '#f44336' : '#4caf50';
        
        const probabilityCell = document.createElement('td');
        probabilityCell.textContent = `${Math.round(item.result.probability * 100)}%`;
        
        const timeCell = document.createElement('td');
        const date = new Date(item.timestamp);
        timeCell.textContent = date.toLocaleString('zh-CN');
        
        row.appendChild(ageCell);
        row.appendChild(sexCell);
        row.appendChild(resultCell);
        row.appendChild(probabilityCell);
        row.appendChild(timeCell);
        
        tableBody.appendChild(row);
    });
    
    // 如果没有历史记录，显示提示信息
    if (sortedHistory.length === 0) {
        const row = document.createElement('tr');
        const cell = document.createElement('td');
        cell.colSpan = 5;
        cell.textContent = '暂无预测历史记录';
        cell.style.textAlign = 'center';
        cell.style.color = '#999';
        row.appendChild(cell);
        tableBody.appendChild(row);
    }
}